package leetCode.hw.string;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Ipv4ToInt {

    public static void main(String[] args) {
        System.out.println(integer2Ip(ip2Integer("0.0.0.0")));
    }

    /**
     * IPv4地址转换为int类型数字
     */
    public static int ip2Integer(String ipv4Addr) {
        // 判断是否是ip格式的
        if (!isIPv4Address(ipv4Addr))
            throw new RuntimeException("Invalid ip address");
        // 匹配数字
        Pattern pattern = Pattern.compile("\\d+");
        Matcher matcher = pattern.matcher(ipv4Addr);
        int result = 0;
        int counter = 0;
        while (matcher.find()) {
            int value = Integer.parseInt(matcher.group());
            result = (value << 8 * (3 - counter++)) | result;
        }
        return result;
    }

    /**
     * 127.0.0.1
     * 判断是否为ipv4地址
     */
    private static boolean isIPv4Address(String ipv4Addr) {
        // 0-255的数字
       boolean result = true;
       String[] params = ipv4Addr.split("\\.");
       if(params.length==4) {
           for(String str:params) {
               try {
                   int a = Integer.parseInt(str);
                   if(a<0||a>255) {
                       result = false;
                       break;
                   }
               }
               catch (Exception e){
                   result = false;
                   break;
               }
           }
       }
       else result = false;
       return result;
    }

    /**
     * 将int数字转换成ipv4地址
     */
    public static String integer2Ip(int ip) {
        StringBuilder sb = new StringBuilder();
        int num = 0;
        boolean needPoint = false; // 是否需要加入'.'
        for (int i = 0; i < 4; i++) {
            if (needPoint) {
                sb.append('.');
            }
            needPoint = true;
            int offset = 8 * (3 - i);
            num = (ip >> offset) & 0xff;
            sb.append(num);
        }
        return sb.toString();
    }

}
